package com.zucc.eye.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zucc.eye.dto.IssueDto;
import com.zucc.eye.dto.RepoDto;
import com.zucc.eye.entity.Issue;
import com.zucc.eye.entity.Repo;
import com.zucc.eye.repository.RepoRepository;
import com.zucc.eye.util.JsonUtil;
import com.zucc.eye.util.OkHttpUtil;
import com.zucc.eye.util.ReturnT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description repo
 * @author zhengkai.blog.csdn.net
 * @date 2022-02-12
 */

@Slf4j
@Api(tags = "repo")
@CrossOrigin
@RestController
@RequestMapping("/repo")
public class RepoController {

    @Autowired
    private RepoRepository repoRepository;

    /**
    * 新增或编辑
    */
    @PostMapping("/save")
    @ApiOperation(value = "save Repo", notes = "save Repo")
    public Object save(@RequestBody Repo repo){
        try {
            return ReturnT.success(repoRepository.save(repo));
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnT.error("保存失败");
        }

    }

    /**
    * 删除
    */
    @PostMapping("/delete")
    @ApiOperation(value = "delete Repo", notes = "delete Repo")
    public Object delete(int id){
        Optional<Repo> repo=repoRepository.findById(id);
        if(repo.isPresent()){
            repoRepository.deleteById(id);
            return ReturnT.success("删除成功");
        }else{
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
    * 查询
    */
    @PostMapping("/find")
    @ApiOperation(value = "find Repo by id", notes = "find Repo by id")
    public Object find(int id){
        Optional<Repo> repo=repoRepository.findById(id);
        if(repo.isPresent()){
            return ReturnT.success(repo.get());
        }else{
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
    * 分页查询
    */
    @PostMapping("/list")
    @ApiOperation(value = "list Repo", notes = "list Repo")
    public Object list(@RequestBody Repo repo,
                        @RequestParam(required = false, defaultValue = "0") int pageNumber,
                        @RequestParam(required = false, defaultValue = "10") int pageSize) {

            try {
                //创建匹配器，需要查询条件请修改此处代码
                ExampleMatcher matcher = ExampleMatcher.matchingAll();

                //创建实例
                Example<Repo> example = Example.of(repo, matcher);
                //分页构造
                Pageable pageable = PageRequest.of(pageNumber,pageSize);

                return ReturnT.success(repoRepository.findAll(example, pageable));

            } catch (Exception e) {
                e.printStackTrace();
                return ReturnT.error(e.getMessage());
            }

    }

    ////获取的是 github首页信息
    //@PostMapping("/issues")
    //@ApiOperation(value = "save Issue", notes = "save Issue")
    //public Object issues(@RequestBody Issue issue) {
    //    String url = issue.getUrl();
    //    String s = OkHttpUtil.get(url, null);
    //    log.info("s {}", s);
    //    //List<Issue> issues = JSONObject.parseArray(s, Issue.class);
    //    List<IssueDto> issueDtos = JSONObject.parseArray(s, IssueDto.class);
    //    List<Issue> collect = issueDtos.stream().map(o -> {
    //        Issue issue1 = o.toEntity();
    //        return issue1;
    //    }).collect(Collectors.toList());
    //    is
    //
    //
    //    JSONArray objects = JSONObject.parseArray(s);
    //    log.info("objects {}", objects);
    //    //https://api.github.com/repos/moshowgame/SpringBootCodeGenerator/issues
    //    //JSONObject json = OkHttpUtil.getJson(url, null);
    //    //log.info("json {}", json);
    //    return ReturnT.success(objects);
    //}
    //获取的是 github首页信息
    @PostMapping("/reqIssNum")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    public Object reqIssNum(@RequestBody Issue issue) {

        //https://api.github.com/repos/moshowgame/SpringBootCodeGenerator
        try{
            String url = issue.getUrl();
            //直接更新吧
//        HttpUtil.
//                httpUtil.get
//        okhttp3 异步 怎么在springboot里面返回

            String string = OkHttpUtil.get(url, null);
            JSONObject jsonObject = JsonUtil.stringToJson(string);
            //这是所有的 info
            //是所有的列表吗
            log.info("jsonObject {}", jsonObject);
            //Repo
            RepoDto repoDto =
                    JSONObject.parseObject(String.valueOf(jsonObject), RepoDto.class);
            Repo repo = repoDto.toEntity();
            //repo
            repoRepository.save(repo);
            Integer open_issues = jsonObject.getInteger("open_issues");
            log.info(" open_issues {} ", open_issues);
            return ReturnT.success(open_issues);
        }catch (Exception e){
            e.printStackTrace();
            return  ReturnT.error(e.getMessage());
        }



        //okhttp3.Request request = new okhttp3.Request.Builder().
        //        url(url).get().build();
        //OkHttpClient okHttpClient = new OkHttpClient();
        //final Call call = okHttpClient.newCall(request);
        //call.enqueue(new Callback() {
        //    @Override
        //    public void onFailure(Call call, IOException e) {
        //        log.info("getMessage {}", e.getMessage());
        //    }
        //
        //    @Override
        //    public void onResponse(Call call, okhttp3.Response response) throws IOException {
        //        String string = response.body().string();
        //        //string不能调用两次 被调用一次就关闭了，这里调用两次会报异常
        //        //JSONObject.toString
        //        //JsonUtil.
        //        //str转化 json alibaba
        //        //total_issues = repoInfo.open_issues;
        //        JSONObject jsonObject = JsonUtil.stringToJson(string);
        //        //这是所有的 info
        //        //是所有的列表吗
        //        log.info("jsonObject {}", jsonObject);
        //        Integer open_issues = jsonObject.getInteger("open_issues");
        //        log.info(" open_issues {} ", open_issues);
        //
        //    }
        //});

//————————————————
//        版权声明：本文为CSDN博主「_无问西东」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/weixin_36709064/article/details/81637693
    }


}